const dayjs = require('dayjs');
const config = require('./config');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

// HardSourceWebpackPlugin是webpack的插件，为模块提供中间缓存步骤。为了查看结果，您需要使用此插件运行webpack两次：第一次构建将花费正常的时间。第二次构建将显着加快（大概提升90%的构建速度）。
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

let webpackPlugins = [];

if (process.env.PATH_ENV === 'production') {
    webpackPlugins = [
        new UglifyJsPlugin({
            uglifyOptions: {
                minimize: true,
                sourceMap: true,
                parallel: true,
                compress: {
                    // 把alert 转化为console.log
                    global_defs: {
                        '@alert': 'console.log'
                    },
                    // 去掉console.log
                    drop_console: true
                }
            }
        })

        // new webpack.BannerPlugin({     banner: `www.turingtopia.com ${config.verison}
        // | by turingtopia.com Team  (c) ${new Date().getFullYear()     } |
        // ${dayjs().format('YYYY-MM-DD HH:mm:ss SSS [Z] A')}` })
    ];
}

let hardSourceWebpackPlugin =
    // new HardSourceWebpackPlugin({
    //     cacheDirectory: '.cache/hard-source/[confighash]'
    // })
    new HardSourceWebpackPlugin({
        // Either an absolute path or relative to webpack's options.context.
        cacheDirectory: 'node_modules/.cache/hard-source/[confighash]',
        // Either a string of object hash function given a webpack config.
        configHash: function(webpackConfig) {
            // node-object-hash on npm can be used to build this.
            return require('node-object-hash')({ sort: false }).hash(
                webpackConfig
            );
        },
        // Either false, a string, an object, or a project hashing function.
        environmentHash: {
            root: process.cwd(),
            directories: [],
            files: ['package-lock.json', 'yarn.lock']
        },
        // An object.
        info: {
            // 'none' or 'test'.
            mode: 'none',
            // 'debug', 'log', 'info', 'warn', or 'error'.
            level: 'debug'
        },
        // Clean up large, old caches automatically.
        cachePrune: {
            // Caches younger than `maxAge` are not considered for deletion. They must
            // be at least this (default: 2 days) old in milliseconds.
            maxAge: 2 * 24 * 60 * 60 * 1000,
            // All caches together must be larger than `sizeThreshold` before any
            // caches will be deleted. Together they must be at least this
            // (default: 50 MB) big in bytes.
            sizeThreshold: 50 * 1024 * 1024
        }
    });

module.exports = {
    mode: 'universal',
    env: {
        PATH_ENV: process.env.PATH_ENV,
        NODE_ENV: process.env.NODE_ENV
    },
    /*
     ** Headers of the page
     */
    head: {
        titleTemplate: titleChunk => {
            // If undefined or blank then we don't need the hyphen
            return titleChunk ? `${titleChunk} - demo` : 'demo';
        },
        meta: [
            {
                charset: 'utf-8'
            },
            {
                name: 'viewport',
                content: 'width=device-width, initial-scale=1, user-scalable=no'
            },
            {
                name: 'version',
                content: config.verison,
                time: dayjs().format('YYYY-MM-DD HH:mm:ss SSS [Z] A') // 展示
            }
        ],
        link: [
            {
                rel: 'icon',
                type: 'image/x-icon',
                href: '/favicon.ico'
            }
        ]
    },
    /*
     ** Customize the progress-bar color
     */
    loading: {
        color: '#fff'
    },
    router: {
        middleware: ['auth']
    },
    /*
     ** Global CSS
     */
    css: [
        'element-ui/lib/theme-chalk/index.css',
        '~assets/less/normalize.less'
    ],
    /*
     ** Plugins to load before mounting the App
     */
    plugins: [
        '@/plugins/element-ui',
        '~/plugins/axios',
        '~/plugins/platform',
        '~/plugins/point',
        {
            src: '~/plugins/day',
            ssr: true
        }
    ],

    server: {
        port: config.PORT, // default
        host: '0.0.0.0', // default: localhost,
        timing: {
            total: true
        }
    },

    // 中间件的调用
    router: {
        middleware: 'auth'
    },

    /*
     ** Nuxt.js dev-modules
     */
    buildModules: [],
    /*
     ** Nuxt.js modules
     */
    modules: ['@nuxtjs/axios'],
    // axios: {
    //       baseURL: location.origin
    //   },
    /*
     ** Build configuration
     */
    build: {
        transpile: [/^element-ui/],
        analyza: {
            analyzeMode: 'static'
        },

        // publicPath: process.env.PATH_ENV === 'production' ? config.cdn : '',

        plugins: webpackPlugins,

        extractCSS: true,
        /*
         ** You can extend webpack config here
         */
        extend(config, ctx) {
            if (ctx.isDev) {
                config.plugins.push(hardSourceWebpackPlugin);
            }
        }
    }
};
